Home:ALL Converter>Load Google Maps JS API in component [Angular]

Load Google Maps JS API in component [Angular]

Ask Time:2018-01-07T14:41:51         Author:Hamid Asghari

Json Formatter

How is it possible to load an external js file, from a url in an Angular component?

To be specific, I'm trying to load google-maps-api to my angular project. Currently, I'm doing it in my index.html like this:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>

Note: I'm aware of angular-maps. That's not an option.

Author:Hamid Asghari,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48134937/load-google-maps-js-api-in-component-angular
John :

You can use Promise to load google API asynchronously whenever you want.\n\n// map-loader.service.ts\nimport ...\ndeclare var window: any;\n\n@Injectable()\nexport class MapLoader {\n\n private static promise;\n map: google.maps.Map;\n\n public static load() {\n if (!MapLoader.promise) { // load once\n MapLoader.promise = new Promise((resolve) => {\n window['__onGapiLoaded'] = (ev) => {\n console.log('gapi loaded')\n resolve(window.gapi);\n }\n console.log('loading..')\n const node = document.createElement('script');\n node.src = 'https://maps.googleapis.com/maps/api/js?key=<YOUR _API_KEY>&callback=__onGapiLoaded';\n node.type = 'text/javascript';\n document.getElementsByTagName('head')[0].appendChild(node);\n });\n }\n\n return MapLoader.promise;\n }\n\n initMap(gmapElement, lat, lng) {\n\n return MapLoader.load().then((gapi) => {\n this.map = new google.maps.Map(gmapElement.nativeElement, {\n center: new google.maps.LatLng(lat, lng),\n zoom: 12\n });\n });\n }\n}\n\n\nComponent\n\n//maps.component.ts\n\n...\n@Component({\n selector: 'maps-page',\n templateUrl: './maps.component.html'\n})\nexport class MapsComponent implements OnInit { \n\n @ViewChild('gmap') gmapElement: any;\n constructor(public mapLoader: MapLoader) { }\n\n ngOnInit() {\n\n this.mapLoader.initMap(this.gmapElement, -37.81, 144.96) // await until gapi load\n }\n\n ...\n}\n\n\nComponent HTML\n\n// maps.component.html\n<div #gmap ></div>\n\n\nDon't forget to add CSS to the element.",
2018-02-20T01:16:23
yy